<?php

class MenuController extends SBaseController
{
	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='main';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
        $this->layout="detail";
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Menu;
        $model->sorder = Common::getNewestPosition($model);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Menu']))
		{
			$model->attributes=$_POST['Menu'];
			if($model->save())
            {
                //Delete old cache
                $model->deleteCache();
                
                Menu::model()->rebuildSOrder();
                Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Create successfully.'));
				$this->redirect(array('view','id'=>$model->id));
            }
        }
        $this->layout="detail";
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model)
		if(isset($_POST['Menu']))
		{
			$model->attributes=$_POST['Menu'];
			if($model->save())
            {
                //Delete old cache
                $model->deleteCache();
                
                Menu::model()->rebuildSOrder();
                Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Updated successfully.'));
				$this->redirect(array('view','id'=>$model->id));
            }
        }
        $this->layout="detail";
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(isset($_POST['select-row'])&&is_array($_POST['select-row']))
        {
            $ids = $_POST['select-row'];
            $ids = implode(',', $ids);
            Menu::model()->deleteAll("id in ($ids)");
            // delete cache menu by id menu 
            $filters = array();
            $filters['inId'] = $ids;
            $menus = Menu::model()->search($filters);
            if($menus)
            {
                $model = new Menu();
                foreach ( $menus as $item ){
                    //Delete old cache
                    $model->deleteCache();
                }
            }
            Menu::model()->rebuildSOrder();
            $this->redirect(array('admin'));
        }
		elseif(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model= $this->loadModel();

            //Delete old cache
            $model->deleteCache();
            
            $model->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		   if(!isset($_GET['ajax']))
           {
                Menu::model()->rebuildSOrder();
				$this->redirect(array('index'));
            }
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        if(!isset($_GET['ajax']) && isset($_POST['sorder']))
        {
            $ids = $_POST['ids'];
            $sorder = $_POST['sorder'];
            for($i=0; $i<count($ids); $i++){
                $model = Menu::model()->findByPk($ids[$i]);
                $model->sorder = $sorder[$i];
                $model->save();
            }
            Menu::model()->rebuildSOrder();
            Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Rebuild all sort order successfully.'));
        }
		$model=new Menu('search');
        $model->sorder = "";
        $model->status = "";

		if(isset($_GET['Menu'])){
			$model->attributes=$_GET['Menu'];
        }
        $this->layout="list";
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Menu::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='menu-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
    public function actionChangeStatus(){
        if($_POST['ajax']&&$_POST['id']){
            $model = Menu::model()->findByPk($_POST['id']);
            if($model->status == Menu::STATUS_ENABLED) $model->status = Menu::STATUS_DISABLED;
            elseif($model->status == Menu::STATUS_DISABLED) $model->status = Menu::STATUS_ENABLED;
            
            //Delete old cache
            $model->deleteCache();
            
            $model->save();
        }else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }
    public function actionDeleteAll()
    {
        if(isset($_POST['select-row'])&&is_array($_POST['select-row']))
        {
            $ids = $_POST['select-row'];
            foreach($ids as $id){
                $model =  '';
                $model = Menu::model()->findbyPk($id);
                if($model===null) throw new CHttpException(404,'The requested page does not exist.');

                // delete menu item
                MenuItem::model()->deleteAll("menu_id in ($id)");
                
                //Delete old cache
                $model->deleteCache();
            
                $model->delete();
            };
            
            Menu::model()->rebuildSOrder();
            $this->redirect(array('admin'));
        }else{
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
        }
    }
}
